package com.qg.contriller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;

import com.qg.config.WxConfig;


import com.qg.service.QgUserService;
import com.qg.service.user_login.LoginQgUser;
import com.qg.utils.*;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jws.soap.SOAPBinding;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 微信登录的控制器
 */
@Controller
@RequestMapping("/api")
public class WxController {

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private KafKaUtil kafkaUtil;

    @Autowired
    private LoginQgUser localUserService;
    /***
     * 让用户进行授权
     * @return
     */
    @RequestMapping("/wx/toLogin")
    public String toWxLogin() throws Exception {
        //向微信平台授权返回code参数

      return "redirect:"+wxConfig.reqCodeUrl();
    }

    @RequestMapping("/wx/callBack")
    public String callBack(String code)throws Exception{
        //1=====通过地址获取accessToken的json串
        String accessTokenjsonStr= UrlUtils.loadURL(wxConfig.reqAccessTokenUrl(code));
        //2=====写入日志
        kafkaUtil.sendInfoMessage(accessTokenjsonStr);
        //3=====获取json字符串某些值
        JSONObject accessTokenjson=JSONObject.parseObject(accessTokenjsonStr);
        String accessToken=accessTokenjson.getString("access_token");
        String openId=accessTokenjson.getString("openid");

        //=====4通过地址获取用户信息
        String userInfoJsonStr=UrlUtils.loadURL(wxConfig.reqUserInfoUrl(accessToken,openId));
        //=====5写入日志
        kafkaUtil.sendInfoMessage(userInfoJsonStr);
        //=====6获取微信token
        String token=localUserService.createWxUserToken(userInfoJsonStr);
        //7=====将微信token跳转至前端首页
        return "redirect:"+wxConfig.getSuccessUrl()+"?token="+token;
    }
}
